﻿@inject AppState AppState

<StackLayout>
    <Frame BorderColor="Colors.LightBlue" CornerRadius="10" Margin="5" Padding="10">
        <StackLayout>
            @* Input area *@
            <Entry @bind-Text="newText"
                   Placeholder="What's to be done?"
                   OnCompleted="AddItem"
                   IsEnabled="(!isAdding)"
                   HorizontalOptions="LayoutOptions.FillAndExpand" />
            <Button Text="Add"
                    OnClick="AddItem"
                    IsEnabled="(!isAdding && !string.IsNullOrWhiteSpace(newText))" />
            <ActivityIndicator Color="Colors.Orange"
                               IsRunning="isAdding" />
        </StackLayout>
    </Frame>
    <Frame BorderColor="Colors.LightBlue" CornerRadius="10" Margin="5" Padding="10">
        <ScrollView>
            <StackLayout>
                <ProgressBar Margin="new Thickness(10)" Progress="@ItemsPercentComplete" />

                @* List of todos *@
                @if (items == null)
                {
                    <StackLayout Orientation="StackOrientation.Horizontal">
                        <Label Text="Loading..." />
                        <ActivityIndicator Color="Colors.Purple"
                                           IsRunning="true" />
                    </StackLayout>
                }
                else
                {
                    foreach (var item in items)
                    {
                        <TodoEntry Item="item" />
                    }
                }
            </StackLayout>
        </ScrollView>
    </Frame>
</StackLayout>

@code
{
    string newText;
    bool isAdding;

    List<TodoItem> items;

    int ItemsTotal => items?.Count ?? 0;
    int ItemsDone => items?.Count(i => i.IsDone) ?? 0;

    double ItemsPercentComplete => ItemsTotal == 0 ? 0d : (double)ItemsDone / (double)ItemsTotal;

    protected override async Task OnInitializedAsync()
    {
        AppState.OnChange += OnItemsChanged;
        await Task.Delay(5000);
        items = await AppState.TodoDatabase.GetItemsAsync();
    }

    private async Task AddItem()
    {
        isAdding = true;
        StateHasChanged();

        // Create an artificial delay to make the activity indicator show up
        await Task.Delay(500);

        await AppState.TodoDatabase.SaveItemAsync(new TodoItem { Text = newText });

        newText = null;

        isAdding = false;

        items = await AppState.TodoDatabase.GetItemsAsync();
    }

    private async Task OnItemsChanged()
    {
        items = await AppState.TodoDatabase.GetItemsAsync();
        StateHasChanged();
    }
}
